package com.zjj.disk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjj.disk.mapper.DictionaryMapper;
import com.zjj.disk.pojo.Dictionary;
import com.zjj.disk.service.DictionaryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements DictionaryService {

    @Override
    public Dictionary getById(Long id) {
        return baseMapper.selectById(id); // 使用 MyBatis-Plus 的 selectById 方法获取记录
    }

    @Override
    @Transactional
    public Dictionary addParent(Dictionary parent) {
        saveOrUpdate(parent); // 保存到数据库
        return parent;
    }

    @Override
    @Transactional
    public Dictionary addChild(Dictionary child, String parentCode) {
        child.setParentCode(parentCode); // 设置父类编码
        save(child); // 保存到数据库
        return child;
    }

    @Override
    @Transactional
    public synchronized void deleteDictionary(Long id) {
        try {
            // 查询要删除的字典项
            Dictionary dictionary = getById(id);
            if (dictionary == null) {
                throw new RuntimeException("Dictionary not found with ID: " + id);
            }

            // 查询所有 parentCode 等于该字典项 code 的子项
            List<Dictionary> children = list(new QueryWrapper<Dictionary>().eq("parent_code", dictionary.getCode()));

            // 删除所有子项
            if (!children.isEmpty()) {
                List<Long> childIds = children.stream().map(Dictionary::getId).collect(Collectors.toList());
                removeBatchByIds(childIds);
            }

            // 删除该字典项
            removeById(id);
        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
            // 抛出自定义异常或进行其他错误处理
            throw new RuntimeException("Failed to delete dictionary with ID: " + id, e);
        }
    }

    @Override
    public IPage<Dictionary> listByParentCode(String parentCode, Page<Dictionary> page) {
        LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        if (parentCode == null) {
            queryWrapper.isNull(Dictionary::getParentCode); // 查询所有父类
        } else {
            queryWrapper.eq(Dictionary::getParentCode, parentCode); // 查询指定父类编码的子类
        }
        // 添加排序条件
        queryWrapper.orderByAsc(Dictionary::getSort); // 按照 sort 字段升序排序
        return page(page, queryWrapper);
    }

    @Override
    public List<Dictionary> getByParentCode(String parentCode) {
        return baseMapper.selectByParentCode(parentCode);
    }
}
